#include"DemoRevoluteJoint.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"Tool.h"

USING_NS_CC;

bool DemoRevoluteJoint::init()
{
	if (!AbstractLayer::init(b2Vec2(0, -10)))
	{
		return false;
	}
	return true;
}

void DemoRevoluteJoint::box2DAppReady()
{
	createBodies();
	createCar();
}

void DemoRevoluteJoint::createCar()
{
	b2Body* carBody = LSYEasyBody::createBox(b2Vec2(100,60), b2Vec2(30, 30));
	b2PolygonShape* shape = new b2PolygonShape;
	shape->SetAsBox(30 * PTM_RADIO, 30 * PTM_RADIO, b2Vec2(-30 * PTM_RADIO, 0), 0);
	carBody->CreateFixture(shape, 1);
	shape->SetAsBox(30 * PTM_RADIO, 30 * PTM_RADIO, b2Vec2(30 * PTM_RADIO, 0), 0);
	carBody->CreateFixture(shape, 1);

	bodyA = LSYEasyBody::createCircle(b2Vec2(70, 15), 15);
	bodyA->GetFixtureList()->SetFriction(10);
	b2Body* bodyB = LSYEasyBody::createCircle(b2Vec2(130,15), 15);
	b2Vec2 anchor = bodyA->GetPosition();

	b2RevoluteJointDef* jointDef = new b2RevoluteJointDef;
	jointDef->Initialize(carBody, bodyA, anchor);
	jointDef->enableMotor = false;
	jointDef->maxMotorTorque = 80;
	jointDef->motorSpeed = 0;
	b2RevoluteJoint* joint1 = (b2RevoluteJoint*)pWorld->CreateJoint(jointDef);
	
	anchor = bodyB->GetPosition();
	jointDef->Initialize(carBody, bodyB, anchor);
	jointDef->enableMotor = false;
	b2RevoluteJoint* joint2 = (b2RevoluteJoint*)pWorld->CreateJoint(jointDef);
	motor = joint1;
}

void DemoRevoluteJoint::createBodies()
{
	auto size = Director::getInstance()->getWinSize();
	LSYEasyBody::createRectangle(b2Vec2(0, 0), size.width, size.height);
	LSYEasyBody::createCircle(b2Vec2(350, 0), 100, b2BodyType::b2_staticBody);
}

void DemoRevoluteJoint::onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
	switch (keyCode)
	{
	case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
		bodyA->SetAngularVelocity(MOTOR_SPEED);
		motor->EnableMotor(true);
		motor->SetMotorSpeed(MOTOR_SPEED);
		break;
	case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
		bodyA->SetAngularVelocity(-MOTOR_SPEED);
		motor->EnableMotor(true);
		motor->SetMotorSpeed(-MOTOR_SPEED);
		break;
	case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
		motor->EnableMotor(true);
		motor->SetMotorSpeed(0);
		break;
	case EventKeyboard::KeyCode::KEY_UP_ARROW:
		motor->EnableMotor(false);
		break;
	default:
		break;
	}
}

void DemoRevoluteJoint::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
}
